package com.dragon.service.impl;

import cn.hutool.core.io.FileUtil;
import com.dragon.mapper.RecordMapper;
import com.dragon.mapper.UserMapper;
import com.dragon.pojo.Record.RecordInfo;
import com.dragon.pojo.Record.RecordList;
import com.dragon.pojo.Record.RecordListResult;
import com.dragon.pojo.Record.RecordSelectInfo;
import com.dragon.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public RecordListResult getRecord(RecordSelectInfo info) {
        info.setOffset((info.getPageNumber()-1)*info.getListNumber());
        List<RecordList> recordList = recordMapper.getRecord(info);

        return new RecordListResult(recordList, recordMapper.getRecordTotal(info));
    }

    @Override
    public RecordInfo getRecordInfo(Integer recordId, Integer userId) {
        RecordInfo recordInfo = recordMapper.getRecordInfo(recordId);
        if(userId != null) {
            if(recordInfo.getUserId().equals(userId)) {
                recordInfo.setSourceCode(FileUtil.readUtf8String(recordInfo.getCodePath()));
            } else if(userMapper.getUserCodePublic(recordInfo.getUserId()) == 1) {
                recordInfo.setSourceCode(FileUtil.readUtf8String(recordInfo.getCodePath()));
            }
        }
        return recordInfo;
    }
}
